package com.marveal.rabbit.producer.service;

import com.marveal.rabbit.producer.constant.BrokerMessageStatus;
import com.marveal.rabbit.producer.entity.BrokerMessage;
import com.marveal.rabbit.producer.mapper.BrokerMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

public class MessageStoreService {

    @Autowired
    private BrokerMessageMapper brokerMessageMapper;

    public MessageStoreService() {
    }

    public int insert(BrokerMessage brokerMessage) {
        return this.brokerMessageMapper.insert(brokerMessage);
    }

    public BrokerMessage selectByMessageId(String messageId) {
        return brokerMessageMapper.selectByPrimaryKey(messageId);
    }

    public void success(String messageId) {
        brokerMessageMapper.changeBrokerMessageStatus(messageId,
                BrokerMessageStatus.SEND_OK.getStatus(),
                new Date());
    }

    public void failure(String messageId) {
        brokerMessageMapper.changeBrokerMessageStatus(messageId,
                BrokerMessageStatus.SEND_FAIL.getStatus(),
                new Date());
    }

    public List<BrokerMessage> fetchTimeOutMessage4Retry(BrokerMessageStatus brokerMessageStatus){
        return brokerMessageMapper.queryBrokerMessageStatus4Timeout(brokerMessageStatus.getStatus());
    }

    public int updateTryCount(String brokerMessageId) {
        return brokerMessageMapper.update4TryCount(brokerMessageId, new Date());
    }

}
